﻿namespace Deppton.Model
{
    using System;
    using System.Collections.Generic;
    using System.Linq;

    public class NamedList<TValue> : List<TValue>
    {
        private Func<TValue, string> nameResolver;

        public NamedList(Func<TValue, string> nameResolver)
        {
            this.nameResolver = nameResolver;
        }

        public TValue this[string key]
        {
            get
            {
                return this.FirstOrDefault(i => string.Equals(this.nameResolver.Invoke(i), key, StringComparison.OrdinalIgnoreCase));
            }
            set
            {
                if (this[key] != null)
                {
                    this.Remove(this.Single(v => string.Equals(nameResolver.Invoke(v), key, StringComparison.OrdinalIgnoreCase)));
                }

                if (value != null)
                {
                    this.Add(value);
                }
            }
        }
    }
}
